/** * ITHUI® * ITHUI-Withdraw适用于余额管理、提现页面，兼容小程序、APP、H5，兼容H5、小程序、APP。 * Copyright (c) 2023 ITHANG All rights reserved. * Licensed (
http://www.apache.org/licenses/LICENSE-2.0 ) * 复制使用请保留本段注释，感谢支持开源！ * * 作者主页 * https://ithang.cn/ * * 开源地址: * https://github.com/ithang-cn/ITHUI-Withdraw
* https://gitee.com/ithang-cn/ITHUI-Withdraw * */

<template>
  <view class="ithui-content">
    <u-overlay :show="sssssssss" @click="show = false"></u-overlay>
    <view class="withdraw">
      <view class="withdraw-head">
        <view class="withdraw-head-to">到账渠道</view>
        <view class="withdraw-head-way">
          <view class="withdraw-head-way-1">
            <image class="way-icon" src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/07/28/money_20250728092852A029.png"></image>
            <text class="way-text">微信零钱</text>
          </view>
          <view class="withdraw-head-way-2">仅支持整数，72小时内到账</view>
        </view>
      </view>
      <view class="withdraw-body">
        <text>提现金额</text>
        <view class="input-money">
          <text class="rmb">￥</text>
          <!-- @focus.prevent="stopKeyborad" -->
          <input v-model.number="extract" @input="onInput" type="digit" class="t-input" :disabled="!aaabbb" />
        </view>
        <view class="info-money">
          <view v-if="is_out">
            <text class="info-money-num" style="color: #ff1e0f">输入金额超过可提现余额，账户余额{{ pool }}元</text>
          </view>
          <view v-else-if="is_lowest">
            <text class="info-money-num" style="color: #ff1e0f">最低{{ lowest }}元起提现，账户余额{{ pool }}元</text>
          </view>
          <view v-else>
            <text class="info-money-num" v-if="aaabbb">当前可提现余额{{ pool }}元，</text>
            <text class="info-money-all" v-if="aaabbb" @click="getAll">全部提现</text>
          </view>
        </view>
        <view :class="'tx' + (is_post ? '-active' : '')"><button @click="handleShowModel">提现</button></view>
      </view>

      <!-- <view :class="['keyboard', keyboradShow ? '' : 'active', isIphoneX ? 'isIphone' : '']">
        <block v-for="(item, index) in 9" :key="index">
          <view class="keyboard-item" @tap="keyboradKey(index + 1)">{{ index + 1 }}</view>
        </block>
        <view class="keyboard-item hide"></view>
        <view class="keyboard-item" @tap="keyboradKey(0)"><text>0</text></view>
        <view class="keyboard-item delte" @tap="keyboradDel()">
          <image class="img" src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/07/28/del_20250728092945A030.png" mode="aspectFill" :lazy-load="true"></image>
        </view>
      </view> -->
      <u-modal
        :show="showModal"
        title="提现确认"
        showCancelButton
        cancelText="我再想想"
        confirmColor="#ff1e0f"
        confirmText="确认提现"
        @confirm="debouncedShenqingtixian"
        @cancel="showModal = false"
      >
        <view class="slot-content">
          <rich-text :nodes="content"></rich-text>
        </view>
      </u-modal>
    </view>
  </view>
</template>

<script>
/* import { getUserInfo, transferToUsers,  } from '../../../utils/request_api';
import { getMerListSum } from '../../../utils/api/local.js'; */
import { getUserInfo, transferToUser, merchantOpenid } from '../../utils/merorder/mer';
export default {
  data() {
    return {
      pool: 0,
      extract: '',
      service_fee: 0.0,
      showModal: false,
      is_out: false,
      is_lowest: false,
      is_post: false,
      lowest: 0.1,
      fee: 0,
      money: '',
      real_money: '',
      keyboradShow: false,
      isIphoneX: false,
      isRefuse: false,
      content: '',
      userData: {},
      aaabbb: true,
      sssssssss: false,
      tixianok: false
    };
  },
  watch: {
    extract(oldVal, newVal) {}
  },
  onShow() {
    this.showloginJs();
  },
  onLoad(options) {
    uni.showLoading({
      title: '加载中'
    });
    this.debouncedShenqingtixian = this.debounce(this.shenqingtixian, 1000); // 初始化防抖方法
    if (options.type == 'invite') {
      this.inviteDatam();
    } else {
      this.initData();
    }
    setTimeout(() => {
      uni.hideLoading();
    }, 500);
  },
  methods: {
    onInput(e) {
      // 实时检查输入金额并更新样式状态
      this.$nextTick(() => {
        this.checkMoney();
      });
    },
    showloginJs() {
      let that = this;
      uni.login({
        provider: 'weixin',
        success: (res) => {
          if (res.code) {
            that.wechatLogin(res.code);
          } else {
            console.error('登录失败:', res.errMsg);
            uni.showToast({
              title: '微信登录失败，请稍后再试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('登录失败:', err);
          uni.showToast({
            title: '微信登录失败，请稍后再试',
            icon: 'none'
          });
        }
      });
    },
    wechatLogin(code) {
      var that = this;
      merchantOpenid({ code: code, merId: uni.getStorageSync('merId') })
        .then((res) => {
          if (res.code == 200 && res.data == true) {
            /* that.navTo('/pages_sh/myCenter/user_money_add?type=integral'); */
            this.tixianok = true;
          } else {
            console.log('🚀🚀 ~ wechatLogin ~ res:', res);
            uni.showToast({
              title: '微信登录失败，请稍后再试',
              icon: 'none'
            });
          }
        })
        .catch((err) => {
          console.log('🚀🚀 ~ wechatLogin ~ err:', err);
          uni.showToast({
            title: '网络请求失败，请稍后再试',
            icon: 'none'
          });
        });
    },
    debounce(func, wait) {
      let timeout;
      return function (...args) {
        const context = this;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
      };
    },
    shenqingtixian() {
      uni.showLoading({
        title: '加载中'
      });
      transferToUser({ ebMerId: uni.getStorageSync('merId'), transferAmount: parseInt(this.extract * 100), type: 1 }).then((res) => {
        if (res.code == 200 && res.data.state == 'WAIT_USER_CONFIRM') {
          this.tixian(res.data.packageInfo);
        } else {
          uni.hideLoading();
          uni.showToast({ title: '提现失败了，请检查是否存在待确认的记录', icon: 'none' });
          this.showModal = false;
        }
      });
    },
    /* 提现 */
    tixian(packageInfo) {
      if (wx.canIUse('requestMerchantTransfer')) {
        this.sssssssss = true;
        uni.hideLoading();
        wx.requestMerchantTransfer({
          mchId: '1700455211',
          appId: 'wxffaff0eaf02b3027',
          package: packageInfo,
          success: (res) => {
            this.showModal = false;
            this.sssssssss = false;
            this.initData();
            uni.showToast({ title: '提现成功！', icon: 'none' });
            setTimeout(() => {
              uni.navigateBack();
            }, 500);
          },
          fail: (res) => {
            uni.showToast({ title: '取消操作', icon: 'none' });
            this.showModal = false;
            this.sssssssss = false;
          }
        });
      } else {
        uni.hideLoading();
        wx.showModal({
          content: '你的微信版本过低，请更新至最新版本。',
          showCancel: false
        });
      }
    },
    async initData() {
      this.userData = await getUserInfo(uni.getStorageSync('merId'));
      console.log('🚀 ~ initData ~ this.userData:', this.userData);
      //   const res = await this.$api.mock("pool");
      //   this.fee = res.fee;
      this.pool = this.userData.data.integraSum;
      this.$nextTick(() => {
        this.keyboradShow = true;
      });
    },
    async inviteDatam() {
      /*   this.inviteData = await getMerListSum({
        type: 3,
        linkId:uni.getStorageSync('merId')
      });
      this.pool = this.inviteData.data.yeSum;
      this.$nextTick(() => {
        this.keyboradShow = true;
      }); */
    },
    stopKeyborad() {
      uni.hideKeyboard();
    },
    keyboradKey(key) {
      this.extract = this.extract * 10 + key;
      this.checkMoney();
    },
    keyboradDel() {
      if (this.extract && this.extract > 0) {
        let val = this.extract / 10;
        if (val == 0) val = '';
        this.extract = val;
        this.checkMoney();
      }
    },
    getAll() {
      this.extract = this.pool;
      this.checkMoney();
    },
    checkMoney() {
      if (!this.extract || this.extract < this.lowest) {
        this.is_lowest = true;
        this.is_post = false;
      } else if (this.extract > this.pool) {
        this.is_out = true;
        this.is_lowest = false;
        this.is_post = false;
      } else {
        this.is_out = false;
        this.is_lowest = false;
        this.is_post = true;
      }
      if (parseFloat(this.extract).toString() == 'NaN') {
        this.is_post = false;
        uni.showToast({
          title: '输入金额不合法',
          icon: 'none'
        });
      }
    },
    handleShowModel() {
      if (!this.tixianok) {
        uni.showToast({
          title: '微信获取信息失败,请稍后再试',
          icon: 'none'
        });
        this.showloginJs();
        return;
      }
      if (this.isRefuse) return;
      this.checkMoney();
      if (!this.is_post) return;
      this.money = this.extract;
      this.service_fee = Number((this.extract * (this.fee / 100)).toString().match(/^\d+(?:\.\d{0,2})?/));
      this.real_money = Number((this.extract - this.service_fee).toString().match(/^\d+(?:\.\d{0,2})?/));
      this.content = `<p>提现金额：<em style="font-style:normal;color:#ff1e0f">${this.money} 元</p>
				          <p>实际到账：<em style="font-style:normal;color:#ff1e0f">${this.real_money} 元</em></p>
				          <p>服务费用：<em style="font-style:normal;color:#ff1e0f">${this.service_fee} 元</em></p>
				          <p>服务费率：<em style="font-style:normal;color:#ff1e0f">${this.fee}%</em></p>
                  <p><em style="font-style:normal;color:#ff1e0f">预计3~5分钟到账，请耐心等待</em></p>
				         `;
      this.showModal = true;
    }
    // getMoney() {
    //   this.showModal = false;
    //   if (this.isRefuse) return;
    //   this.isRefuse = true;
    //   setTimeout(() => {
    //     uni.showToast({
    //       title: "提现申请已提交，等待审核",
    //       mask: false,
    //       icon: "none",
    //     });
    //   }, 500);
    //   setTimeout(() => {
    //     uni.navigateBack();
    //   }, 1000);
    // },
  },
  onPullDownRefresh() {
    this.extract = '';
    this.initData();
    this.is_out = false;
    this.is_lowest = false;
    this.is_post = false;
    setTimeout(function () {
      uni.stopPullDownRefresh();
    }, 500);
  }
};
</script>

<style>
page {
  background-color: #ededed;
}
</style>

<style lang="scss" scoped>
::v-deep .u-modal__content {
  justify-content: flex-start;
}

.ithui {
  &-content {
    .withdraw {
      padding: 40rpx;

      &-head {
        background-color: #f7f7f7;
        display: flex;
        align-content: center;
        padding: 40rpx 60rpx;
        font-size: 28rpx;

        &-to {
        }

        &-way {
          display: flex;
          flex-direction: column;
          align-content: center;
          margin-left: 40rpx;

          &-1 {
            color: #576b95;
            margin-bottom: 20rpx;

            .way-icon {
              width: 36rpx;
              height: 36rpx;
              margin-right: 10rpx;
              top: 4rpx;
            }
          }

          &-2 {
            color: #acacac;
            font-size: 26rpx;
          }
        }
      }

      &-body {
        background-color: #fff;
        padding: 40rpx 60rpx;
        font-size: 28rpx;

        .input-money {
          display: flex;
          align-content: center;
          font-weight: 600;
          border-bottom: 1rpx solid #eaeef1;

          .rmb {
            font-size: 2em;
            top: 20rpx;
            position: relative;
          }

          .t-input {
            height: 1.9em;
            font-size: 2.5em;
            border: none;
            position: relative;
            left: 3.5%;
            outline: none;
          }
        }

        .info-money {
          margin-top: 20rpx;
          font-size: 24rpx;
          margin-bottom: 40rpx;

          &-num {
            color: #b2b2b2;
          }

          &-all {
            color: #576b95;
          }
        }

        .tx {
          button {
            color: #b2b2b2;
          }
        }

        .tx-active {
          button {
            color: #fff;
            background: #07c160;
          }
        }
      }

      .keyboard {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background: #ebebeb;
        display: flex;
        justify-content: center;
        z-index: 2;
        flex-wrap: wrap;
        transition: all 0.2s ease-in 0.2s;
      }

      .active {
        bottom: -400rpx;
      }

      .keyboard-item {
        box-sizing: border-box;
        width: 250rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: #fff;
        font-size: 40rpx;
        color: #333;
        height: 99rpx;
        border: 1rpx solid #ebebeb;
        border-top: none;
        border-left: none;
      }

      .hide {
        opacity: 0;
      }

      .delte {
        background: none;
        box-shadow: none;
      }

      .delte image {
        width: 60rpx;
        height: 60rpx;
      }

      .isIphone {
        padding-bottom: 68rpx !important;
      }

      .fee {
        em {
          font-size: 0.5rem;
          font-style: normal;
        }
      }
    }
  }
}
</style>
